package me.zhangjin.lucene.demo.es.api;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

public class TestClient {
    private static String CLUSTER_NAME = "kkking";
    private static String HOST_IP = "192.168.1.102";
    private static int TCP_PORT = 19300;

    public static void main(String[] args) throws Exception {
        temp();
    }

    private static void temp() throws Exception {
        try (TransportClient client = getClient()) {
            var qb = matchAllQuery();
            var response = client.prepareSearch("myweibo3")
                    .setTypes("example")
                    .setFrom(0)
                    .setSize(10)
                    .get();

            for (var source : response.getHits().getHits()) {
                System.out.println(source.getSourceAsString());
            }
        }
    }

    /**
     * 创建 TransportClient
     *
     * @return
     * @throws Exception
     */
    private static TransportClient getClient() throws Exception {
        Settings settings = Settings.builder()
                // 开启嗅探模式来自动加入集群
                //.put("client.transport.sniff", true)
                // 此处要指定集群的名称
                .put("cluster.name", CLUSTER_NAME)
                .build();

        // 指定 IP 地址和端口
        InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(HOST_IP), TCP_PORT);

        return new PreBuiltTransportClient(settings).addTransportAddress(address);

    }

    /**
     * 创建基本的连接
     * 获取当前连接的节点名称
     *
     * @throws Exception
     */
    private static void basicConn() throws Exception {
        // 实现了 Cloasable 接口
        // 自动调用 Close 方法关闭
        try (TransportClient client = getClient()) {
            var nodes = client.connectedNodes();
            nodes.forEach(it -> {
                System.out.println(it.getName());
            });
        }
    }

    /**
     * 创建一个索引
     *
     * @throws Exception
     */
    private static void createIndex() throws Exception {
        try (TransportClient client = getClient()) {

            // 创建一个 JSON 对象
            // 还可以使用手工 JOSN 字符串或者 Gson/Jackson 来序列化 Json bean
            XContentBuilder builder = jsonBuilder().startObject()
                    .field("user", "cy")
                    .field("post_date", "2017-01-01T08:00:00")
                    .field("mymessage", "Java Client test")
                    .endObject();

            // 创建 myweibo3 索引（库）
            // 类型为 example（表）
            var response = client
                    // 创建索引
                    .prepareIndex("myweibo3", "example")
                    .setSource(builder)
                    .get();

            // 获得索引名称
            String index = response.getIndex();
            // 获得索引类型
            String type = response.getType();
            // 得到 document id
            String id = response.getId();
            // 得到版本号，如果首次索引该文档，则此值为 1
            long version = response.getVersion();

            System.out.println(index + "\t" + type + "\t" + id + "\t" + version + "\n");
        }
    }

    /**
     * 获取一个文档
     *
     * @throws Exception
     */
    private static void getDocument() throws Exception {
        try (TransportClient client = getClient()) {
            var response = client
                    .prepareMultiGet()
                    // 要指定 id
                    .add("myweibo3", "example", "AW6cXL5oNF85ir4c3FvX")
                    .add("myweibo3", "example", "AW6cXOw3NF85ir4c3FvY")
                    .get();
            for (var data : response.getResponses()) {
                System.out.println(data.getId());
            }
        }
    }
}
